﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MP3Ganizer.Common.Interfaces.FileTree;
using Microsoft.Practices.ServiceLocation;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Input;
using MP3Ganizer.Modules.FileTree.ViewModels;
using MP3Ganizer.BusinessObject.Hierarchy;

namespace MP3Ganizer.Modules.FileTree.Views
{
    [TemplatePart(Name = "PART_trvFile", Type = typeof(ItemsControl))]
    public class FileTreeView : ContentControl, IFileTreeView
    {
        private ItemsControl _trvFile;
        public FileTreeView()
        {
            DataContext = ServiceLocator.Current.GetInstance<IFileTreeViewModel>();
        }
        public IFileTreeViewModel ViewModel
        {

            get { return (IFileTreeViewModel)DataContext; }
        }
        public override void OnApplyTemplate()
        {
            _trvFile= base.GetTemplateChild("PART_trvFile") as ItemsControl;
            if (_trvFile != null)
            {
                _trvFile.MouseMove += new MouseEventHandler(OnMouseMove);
            }
            base.OnApplyTemplate();
        }

        private void OnMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                FrameworkElement originalSource = e.OriginalSource as FrameworkElement;
                if (originalSource != null && originalSource.DataContext is IHierarchy)
                {
                    DragDropEffects effects;
                    DataObject obj = new DataObject();

                    IHierarchy hierarchy = originalSource.DataContext as IHierarchy;
                    IEnumerable<IFileModel> files = null;
                    if (hierarchy is FolderModel)
                    {
                        var folder = hierarchy as FolderModel;
                        files = folder.FileChildren;
                    }
                    else if (hierarchy is FileModel)
                    {
                        files = new IFileModel[1] { hierarchy as IFileModel }.AsEnumerable();
                    }
                    if (files == null)
                        return;

                    obj.SetData(files);
                    effects = DragDrop.DoDragDrop((UIElement)sender, obj, DragDropEffects.Copy | DragDropEffects.Move);
                    e.Handled = true;
                }
            }
        }
    }
}
